// cloudfunctions/setDefaultBankCard/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { userId, cardId } = event
    
    if (!userId || !cardId) {
      return { success: false, message: '参数缺失' }
    }
    
    // 开启事务
    const transaction = await db.startTransaction()
    
    try {
      // 1. 将用户的所有银行卡设为非默认
      await transaction.collection('user_bank_cards')
        .where({ userId: userId })
        .update({
          data: {
            isDefault: false,
            updateTime: db.serverDate()
          }
        })
      
      // 2. 将指定银行卡设为默认
      await transaction.collection('user_bank_cards')
        .doc(cardId)
        .update({
          data: {
            isDefault: true,
            updateTime: db.serverDate()
          }
        })
      
      // 3. 提交事务
      await transaction.commit()
      
      return { success: true, message: '设置默认卡成功' }
      
    } catch (error) {
      await transaction.rollback()
      throw error
    }
    
  } catch (error) {
    console.error('设置默认卡失败:', error)
    return { success: false, message: '设置默认卡失败' }
  }
}